package com.mycompany.project.client.chee;


import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.ValueBoxBase.TextAlignment;
import com.mycompany.project.client.Main;
import com.mycompany.project.client.ModuleType;
import com.mycompany.project.client.neville.QualityCheckGUI;

/**
 * THis is the habitatconfiguration GUI class.
 * @author LeeNou
 *
 */
@SuppressWarnings("deprecation")
public class HabitatConfigurationGUI {
	/**
	 * GUI PANEL.
	 */
	private VerticalPanel verticalPanel = new VerticalPanel();
	/**
	 * ListBox.
	 */
	private ListBox listBox = new ListBox();
	/**
	 * delete file button.
	 */
	private Button btnDeleteFile = new Button("Delete File");
	/**
	 * load file button.
	 */
	private Button btnLoadFile = new Button("Load File");
	/**
	 * save file button.
	 */
	private Button btnSaveFile = new Button("Save File");
	/**
	 * text box.
	 */
	private TextBox textBox = new TextBox();
	/**
	 * file size.
	 */
	private int size = 0;
	/**
	 * confGUI.
	 */
	private ConfigurationGUI confGUI  = new ConfigurationGUI();
	/**
	 * Quality QUI.
	 */
	private QualityCheckGUI qCheck = new QualityCheckGUI();
	/**
	 * Constructor.
	 */
	public HabitatConfigurationGUI() {
		verticalPanel.setHorizontalAlign(HorizontalAlignment.CENTER);
		verticalPanel.setSize("675px", "569px");
		verticalPanel.add(new HTML(
				"<center>Habitat Configuration</center>"));
		HorizontalPanel horizontalPanel = new HorizontalPanel();
		verticalPanel.add(horizontalPanel);
		//place the configuration option and grid
		horizontalPanel.add(getConfGUI().getGUI(0));
		horizontalPanel.add(getConfGUI().getGUI(1));
		//quality check part
		VerticalPanel qualityVpanel = new VerticalPanel();
		HorizontalPanel qualityNSaveLoad = new HorizontalPanel();
		HTML htmlQualityCheck = new HTML(
				"<center><b>Quality Check</b></center>",
				true);
		qualityVpanel.add(htmlQualityCheck);
		qualityVpanel.add(getqCheck().getVerticalPanel());
		qualityNSaveLoad.add(qualityVpanel);
		qualityNSaveLoad.setHorizontalAlign(HorizontalAlignment.CENTER);
		qualityNSaveLoad.setVerticalAlign(VerticalAlignment.MIDDLE);
		//save and load habitat configuration part
		VerticalPanel verticalPanel2 = new VerticalPanel();
		verticalPanel2.setSize("340px", "162px");
		qualityNSaveLoad.add(verticalPanel2);
		verticalPanel2.setHorizontalAlign(HorizontalAlignment.CENTER);
		verticalPanel2.setVerticalAlign(VerticalAlignment.MIDDLE);
		verticalPanel.add(qualityNSaveLoad);
		HTML htmlSaveloadModuleDetails = new HTML(
				"<center><b>Save/Load Habitat "
				+ "Configurations</b></center>",
				true);
		verticalPanel2.add(htmlSaveloadModuleDetails);
		HorizontalPanel horizontalPanel2 = new HorizontalPanel();
		verticalPanel2.add(horizontalPanel2);
		horizontalPanel2.setSize("339px", "99px");
		com.google.gwt.user.client.ui.VerticalPanel verticalPanelT
		= new com.google.gwt.user.client.ui.VerticalPanel();
		verticalPanelT.
		setHorizontalAlignment(
				HasHorizontalAlignment.ALIGN_CENTER);
		horizontalPanel2.add(verticalPanelT);
		HTML htmlfileName = new HTML(
				"<center>File name:</center>",
				true);
		verticalPanelT.add(htmlfileName);
		textBox.setAlignment(TextAlignment.CENTER);
		verticalPanelT.add(textBox);
		textBox.setWidth("142px");
		textBox.setTitle("Enter new save file name");
		verticalPanelT.add(btnSaveFile);
		btnSaveFile.setWidth("150px");
		verticalPanelT.add(btnLoadFile);
		btnLoadFile.setWidth("150px");
		verticalPanelT.add(btnDeleteFile);
		btnDeleteFile.setWidth("150px");
		com.google.gwt.user.client.ui.VerticalPanel verticalPanel_2
		= new com.google.gwt.user.client.ui.VerticalPanel();
		horizontalPanel2.add(verticalPanel_2);
		HTML htmlpreviousSavedFiles = new HTML(
				"<center>Previous saved file(s)</center>",
				true);
		verticalPanel_2.add(htmlpreviousSavedFiles);
		verticalPanel_2.add(listBox);
		listBox.setSize("125px", "95px");
		listBox.setVisibleItemCount(5);
		initAction();
	}
	/**
	 * Get this class's GUI.
	 * @return the GUI.
	 */
	public final VerticalPanel getGUI() {
		return verticalPanel;
	}
	/**
	 * Init load button.
	 */
	private void initLoadBtn() {
		btnLoadFile.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(final ClickEvent event) {
					//check if list box has files
					//and load the selected file
					if (listBox.getItemCount() > 0
							&& Main.getLocal().
							getItem(
									"Habitat Save") !=null) {
						//checks if an item is selected
						if (isFileSelected()) {
							final DialogBox popUp
							= new DialogBox(false);
		    	      		final VerticalPanel popPanel
		    	      		= new VerticalPanel();
		    	      		final HorizontalPanel hPanel
		    	      		= new HorizontalPanel();
		    	      		final Button noBtn = new Button("no");
		    	      		noBtn.setWidth("50px");
		    	      		final Button yesBtn = new Button("yes");
		    	      		yesBtn.setWidth("50px");
		    	      		popPanel.add(
		    	      				new HTML("<center>Load this file?</center>"));
		    	      		popPanel.add(hPanel);
		    	      		popUp.setWidget(popPanel);
		    	      		hPanel.add(yesBtn);
		    	      		hPanel.add(noBtn);
		    	      		popUp.setPopupPosition(400, 100);
		    	      		popPanel.
		    	      		setHorizontalAlign(
		    	      				HorizontalAlignment.CENTER);
		    	      		hPanel.
		    	      		setHorizontalAlign(
		    	      				HorizontalAlignment.CENTER);
		    	      	    popUp.show();
		    	      	  yesBtn.addClickListener(new ClickListener() {
							@Override
							public void onClick(final Widget sender) {
									LoadFromMem(listBox.
											getItemText(listBox.
													getSelectedIndex()));
									MHCSound.
									playFileLoaded();
									popUp.
									hide();
							}
		    	      	  });
		    	       		noBtn.addClickHandler(
		    	       				new ClickHandler() {
		    	       	        public void onClick(final ClickEvent event) {
		    	               			popUp.hide();
		    	       	        } });
						} else {
							Window.alert("No file is"
									+ "selected!");
						}
					} else {
						Window.alert("No files"
								+ "to load!");
					}
			}
		});
	}
	/**
	 * Init save button.
	 */
	private void initSaveBtn() {
		//save button function
		btnSaveFile.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(final ClickEvent event) {
				for (int k = 0; k < ConfigurationGUI.
						MAX_CONFIG; k++) {
					if (ConfigurationGUI.
							getHConfiguration(k).
							getGridList() == null) {
						Window.alert("Cannot save file"
								+ "at the moment.");
						return;
					}
				}
				for (int i = 0; i < listBox.
						getItemCount(); i++) {
					if (listBox.getItemText(i).
							equals(textBox.
									getText())) {
						Window.alert("Sorry, please select"
								+ "a unique file name!");
						return;
					}
				}
				if (textBox.getText().length() > 20) {
					Window.alert("File name must less"
							+ "than 19 characters long.");
				} else if (textBox.getText().length() > 0
						&& textBox.getText().length() < 20) {
						//ask user first before updating
						final DialogBox popUp
						= new DialogBox(false);
	    	      		final VerticalPanel popPanel
	    	      		= new VerticalPanel();
	    	      		final HorizontalPanel hPanel
	    	      		= new HorizontalPanel();
	    	      		final Button noBtn = new Button("no");
	    	      		noBtn.setWidth("50px");
	    	      		final Button yesBtn = new Button("yes");
	    	      		yesBtn.setWidth("50px");
	    	      		popPanel.add(new HTML(
	    	      				"<center>Save new file?</center>"));
	    	      		popPanel.add(hPanel);
	    	      		popUp.setWidget(popPanel);
	    	      		hPanel.add(yesBtn);
	    	      		hPanel.add(noBtn);
	    	      		popUp.setPopupPosition(
	    	      				400, 100);
	    	      		popPanel.
	    	      		setHorizontalAlign(
	    	      				HorizontalAlignment.CENTER);
	    	      		hPanel.
	    	      		setHorizontalAlign(
	    	      				HorizontalAlignment.CENTER);
	    	      	    popUp.show();
	    	      	  yesBtn.addClickListener(new ClickListener() {
						public void onClick(final Widget sender) {
								Main.getLocal().
								setItem("HabitatFile" + size, textBox.getText());
								size++;
								Main.
								getLocal().
								setItem("Habitat Size", "" + size);
								Main.
								getLocal().setItem("Habitat Save", "Yes");//indicates that file is saved
								SaveToMem(textBox.getText());
								MHCSound.playFileSaved();
								//add it to the list box
								listBox.
								addItem(textBox.getText());
								//clear text box
								textBox.setText("");
								popUp.hide();
						}
	    	      	  });
	    	       		noBtn.addClickHandler(new ClickHandler() {
	    	       	        public void onClick(final ClickEvent event) {
	    	               			popUp.hide();
	    	       	        } });
					} else if (textBox.getText().
							length() == 0
							&& listBox.
							getItemCount() >0
							&& isFileSelected()) {
						//ask user first before updating
						final DialogBox popUp
						= new DialogBox(false);
	    	      		final VerticalPanel popPanel
	    	      		= new VerticalPanel();
	    	      		final HorizontalPanel hPanel
	    	      		= new HorizontalPanel();
	    	      		final Button noBtn = new Button("no");
	    	      		noBtn.setWidth("50px");
	    	      		final Button yesBtn = new Button("yes");
	    	      		yesBtn.setWidth("50px");
	    	      		popPanel.add(new HTML(
	    	      				"<center>Overwrite file?</center>"));
	    	      		popPanel.add(hPanel);
	    	      		popUp.setWidget(popPanel);
	    	      		hPanel.add(yesBtn);
	    	      		hPanel.add(noBtn);
	    	      		popUp.setPopupPosition(
	    	      				400, 100);
	    	      		popPanel.
	    	      		setHorizontalAlign(
	    	      				HorizontalAlignment.CENTER);
	    	      		hPanel.
	    	      		setHorizontalAlign(
	    	      				HorizontalAlignment.CENTER);
	    	      	    popUp.show();
	    	      	  yesBtn.addClickListener(new ClickListener() {
						public void onClick(final Widget sender) {
								 for (int j = 0; j < size; j++) {
									 if (Main.getLocal().
											 getItem("HabitatFile"+j).
											 equals(listBox.
													 getItemText(listBox.
															 getSelectedIndex()))) {
										 SaveToMem(Main.
												 getLocal().
												 getItem("HabitatFile"+j));
										 MHCSound.playFileOverwritten();
										 j = size;//exits once done
									 }
								 }
								popUp.hide();
						}
	    	      	  });
	    	       		noBtn.addClickHandler(new ClickHandler() {
	    	       	        public void onClick(ClickEvent event) {
	    	               			popUp.hide();
	    	       	        } });
							} else {
						Window.alert("Please enter in a new save file name");
					}
			}
		});
	}
	/**
	 * Init functions.
	 */
	private void initAction() {
		//if local storage has something in it and
		//key item "Habitat save" is "yes" then
				//that means that we have previous save files
				if (Main.getLocal().getLength() > 0
						&& Main.getLocal().
						getItem(
								"Habitat Save")
								!= null) {
					//get the size of how many save files
					//and store
					//it into int size
				     size = Integer.parseInt(Main.
				    		 getLocal().
				    		 getItem("Habitat Size"));
				     for (int k = 0; k < size; k++) {
							if (Main.getLocal().
									getItem(
											"HabitatFile" + k)
									!= null) {
								listBox.
								addItem(Main.
										getLocal().
										getItem(
												"HabitatFile" + k));
							}
						}
				} else {
					size = 0;
				}
				initSaveBtn();
				initLoadBtn();
				initDeleteBtn();
	}
	/**
	 * Init delete btn.
	 */
	private void initDeleteBtn() {
		btnDeleteFile.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(final ClickEvent event) {
					if(listBox.getItemCount() > 0 )
					{
						//ask user first before updating
						if (isFileSelected()) {
							final DialogBox popUp
							= new DialogBox(false);
	        	      		final VerticalPanel popPanel
	        	      		= new VerticalPanel();
	        	      		final HorizontalPanel hPanel
	        	      		= new HorizontalPanel();
	        	      		final Button noBtn = new Button("no");
	        	      		noBtn.setWidth("50px");
	        	      		final Button yesBtn = new Button("yes");
	        	      		yesBtn.setWidth("50px");
	        	      		popPanel.add(new HTML(
	        	      				"<center>Delete this file?</center>"));
	        	      		popPanel.add(hPanel);
	        	      		popUp.setWidget(popPanel);
	        	      		hPanel.add(yesBtn);
	        	      		hPanel.add(noBtn);
	        	      		popUp.setPopupPosition(
	        	      				400, 100);
	        	      		popPanel.
	        	      		setHorizontalAlign(
	        	      				HorizontalAlignment.CENTER);
	        	      		hPanel.
	        	      		setHorizontalAlign(HorizontalAlignment.CENTER);
	        	      	    popUp.show();
	        	      	  yesBtn.addClickListener(new ClickListener(){
								@Override
								public void onClick(final Widget sender) {
									for (int j = 0; j < ConfigurationGUI.MAX_CONFIG; j++) {
										for (int i = 0; i < size; i++) {
											if (Main.getLocal().
													getItem("HabitatFile"+i) != null
													&& 
											   Main.getLocal().
											   getItem("HabitatFile"+i).
											   equals(listBox.
													   getItemText(
															   listBox.getSelectedIndex()))) {
												for (int l = 0; l < Module.MAX_SIZE; l++) {
													int size = Integer.
															parseInt(Main.
																	getLocal().
																	getItem(listBox.
																			getItemText(
																					listBox.
																					getSelectedIndex()) +
																					"Habitat" + l + "" + j));
										
													for (int k = 0; k < size; k++) {
														String fileName
														= listBox.
														getItemText(
																listBox.
																getSelectedIndex());
														//save the module type
														Main.getLocal().removeItem(fileName+"G_ModuleType"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"G_ModuleCode"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"G_ModulePosX"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"G_ModulePosY"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"GX_ModulePosX"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"GX_ModulePosY"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"G_ModuleStat"+l+""+k+""+j);
														Main.getLocal().removeItem(fileName+"G_ModuleOrient"+l+""+k+""+j);
													}
													Main.getLocal().removeItem(listBox.getItemText(listBox.getSelectedIndex())+"Habitat"+l+""+j);
												}
												//remove from memory
												Main.getLocal().removeItem("HabitatFile"+i);
												i = size;//exits loop after finishes
											}
										}
									}
									//remove from list box
									listBox.removeItem(listBox.getSelectedIndex());
									popUp.hide();
									MHCSound.playFileDeleted();
								}
		        	      	  });
	        	      	noBtn.addClickHandler(new ClickHandler() {
        	       	        public void onClick(ClickEvent event) {
        	               			popUp.hide();
        	       	        } });
						} else {
							Window.alert("No file is selected");
						}
					} else {
						Window.alert("No files to delete");
					}
			}
		});
	}
	/**
	 * Load from file.
	 * @param fileName the name of the file.
	 */
	private void LoadFromMem(final String fileName) {
		for (int k = 0; k < ConfigurationGUI.MAX_CONFIG; k++) {
			ConfigurationGUI.redraw(k);
			ConfigurationGUI.getHConfiguration(k).initList();
			//load save
			for (int i = 0; i < Module.MAX_SIZE; i++) {
				//clears whatever is in the list
				ConfigurationGUI.
				getHConfiguration(k).
				getGridList().get(i).
				clear();
				int m_size = Integer.
						parseInt(Main.
								getLocal().
								getItem(
										fileName + "Habitat" + i + "" + k).trim());
				for (int j = 0; j< m_size; j++) {
					int number = Integer.
							parseInt(Main.
									getLocal().
									getItem(
											fileName + "G_ModuleType" + i + "" + j + "" + k));
					ModuleType mType = Module.
							checkModuleType(number);
					Module m = new Module();
					m.setModuleType(mType);
					m.setCodeNumber(Integer.
							parseInt(Main.
									getLocal().
									getItem(
											fileName + "G_ModuleCode"
									+ i + "" + j + "" + k)));
					m.setPositionX(Integer.parseInt(Main.getLocal().getItem(fileName+"G_ModulePosX"+i+""+j+""+k)));
					
					m.setPositionY(Integer.parseInt(Main.getLocal().getItem(fileName+"G_ModulePosY"+i+""+j+""+k)));
				
					m.setStats(Main.getLocal().getItem(fileName+"G_ModuleStat"+i+""+j+""+k));
					
					m.setOrientation(Integer.parseInt(Main.getLocal().getItem(fileName+"G_ModuleOrient"+i+""+j+""+k)));
					m.setGridX(Integer.parseInt(Main.getLocal().getItem(fileName+"GX_ModulePosX"+i+""+j+""+k)));
					m.setGridY(Integer.parseInt(Main.getLocal().getItem(fileName+"GX_ModulePosY"+i+""+j+""+k)));
					ConfigurationGUI.getHConfiguration(k).getGridList().get(i).add(m);
					//display this to the grid
					getConfGUI().setGrid(k, m);
				}
			}
		}
		ConfigurationGUI.setPlaceBtn(true);
	}
	/**
	 * Save file to memory.
	 * @param fileName the file name.
	 */
	private void SaveToMem(final String fileName) {
		for (int k = 0; k < ConfigurationGUI.MAX_CONFIG; k++) {
			ConfigurationGUI.updateGridList(k);
			for (int i = 0; i <Module.MAX_SIZE; i++) {
				//save  size
				Main.getLocal().
				setItem(fileName+
						"Habitat"
						+ i + "" + k,
						"" + ConfigurationGUI.
						getHConfiguration(k).
						getGridList().get(i).size());
				for (int j = 0; j < ConfigurationGUI.
						getHConfiguration(k).
						getGridList().
						get(i).size(); j++) {
					//save the module type
					Main.getLocal().setItem(fileName+"G_ModuleType"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getModuleType().ordinal());
					//save the code number
					Main.getLocal().setItem(fileName+"G_ModuleCode"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getCodeNumber());
					//save the pos x
					Main.getLocal().setItem(fileName+"G_ModulePosX"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getPositionX());
					//save the pos y
					Main.getLocal().setItem(fileName+"G_ModulePosY"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getPositionY());
					//save the Status
					Main.getLocal().setItem(fileName+"G_ModuleStat"+i+""+j+""+k, ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getStats());
					//save the orientation
					Main.getLocal().setItem(fileName+"G_ModuleOrient"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getOrientation());
					//save g posxy
					Main.getLocal().setItem(fileName+"GX_ModulePosY"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getGridY());
					//save g posx
					Main.getLocal().setItem(fileName+"GX_ModulePosX"+i+""+j+""+k, ""+ConfigurationGUI.getHConfiguration(k).getGridList().get(i).get(j).getGridX());
				}
			}
		}
	}
	/**
	 * Check if a file is selected.
	 * @return true if one is selected.
	 */
	private boolean isFileSelected() {
		for (int i = 0; i < listBox.getItemCount(); i++) {
			if (listBox.isItemSelected(i)) {
				return true;
			}
		}
		return false;
	}
	/**
	 * @return the confGUI
	 */
	public final ConfigurationGUI getConfGUI() {
		return confGUI;
	}
	/**
	 * @param confGUI the confGUI to set
	 */
	public final void setConfGUI(final ConfigurationGUI confGUI) {
		this.confGUI = confGUI;
	}
	/**
	 * @return the qCheck
	 */
	public final QualityCheckGUI getqCheck() {
		return qCheck;
	}
	/**
	 * @param qCheck the qCheck to set
	 */
	public final void setqCheck(final QualityCheckGUI qCheck) {
		this.qCheck = qCheck;
	}

}
